﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.AuthorizeRBAC;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.RBAC.API.Application.Common.Permission;
using RedDragon.RBAC.ErrorCodeEnum;
using SqlSugar;
using T.Common.Domain.Common;

namespace RedDragon.RBAC.API.Application.Common.UserRolePermission
{
    public class CreateRolePermissionHandler : IRequestHandler<CreateRolePermissionCommand, Result>
    {
        private readonly ISqlSugarClient db;
        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 用户角色仓储
        /// </summary>
        public readonly IBaseRepository<RolePermissions> RolePermissionssRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<CreateRolePermissionHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="rolePermissionssRepository"></param>
        /// <param name="logger"></param>
        public CreateRolePermissionHandler(ISqlSugarClient db,IMapper mapper, IBaseRepository<RolePermissions> rolePermissionssRepository, ILogger<CreateRolePermissionHandler> logger)
        {
            this.db = db;
            this.mapper = mapper;
            RolePermissionssRepository = rolePermissionssRepository;
            this.logger = logger;
        }
        /// <summary>
        /// 角色权限添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(CreateRolePermissionCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                var list = new List<RolePermissions>();
                for (int i = 0; i < request.Permissions.Count; i++)
                {
                    RolePermissions dto = new RolePermissions();
                    dto.PermissionId = request.Permissions[i];
                    dto.RolesId = request.RolesId;
                    list.Add(dto);
                }
                var res = RolePermissionssRepository.AddRange(list);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "角色权限添加成功";
                }
            }
            catch (Exception ex)
            {
                logger.LogError("角色权限添加异常" + ex);
                result.Msg = "角色权限添加异常";
            }
            return result;
        }
    }
}
